package com.example.managemyself.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.UUID;

/**
 * AI聊天历史记录管理器
 * 负责保存、加载和管理聊天对话历史
 */
public class ChatHistoryManager {
    
    private static final String TAG = "ChatHistoryManager";
    private static final String PREFS_NAME = "ai_chat_history";
    private static final String KEY_CONVERSATIONS = "conversations";
    private static final String KEY_MESSAGES_PREFIX = "messages_";
    
    private final SharedPreferences prefs;
    private final Gson gson;
    private final SimpleDateFormat dateFormat;
    
    public ChatHistoryManager(Context context) {
        prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        gson = new Gson();
        dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
    }
    
    /**
     * 创建新对话
     */
    public String createNewConversation(String title) {
        String conversationId = UUID.randomUUID().toString();
        String timestamp = dateFormat.format(new Date());
        
        Conversation conversation = new Conversation(conversationId, title, timestamp);
        
        // 获取现有对话列表
        List<Conversation> conversations = getAllConversations();
        conversations.add(0, conversation); // 添加到开头
        
        // 保存对话列表
        saveConversations(conversations);
        
        Log.d(TAG, "Created new conversation: " + conversationId + " - " + title);
        return conversationId;
    }
    
    /**
     * 添加消息到对话
     */
    public void addMessage(String conversationId, int messageType, String content) {
        List<ChatMessage> messages = getConversationMessages(conversationId);
        
        String timestamp = new SimpleDateFormat("HH:mm", Locale.getDefault()).format(new Date());
        ChatMessage message = new ChatMessage(messageType, content, timestamp);
        messages.add(message);
        
        // 保存消息列表
        String messagesKey = KEY_MESSAGES_PREFIX + conversationId;
        String messagesJson = gson.toJson(messages);
        prefs.edit().putString(messagesKey, messagesJson).apply();
        
        // 更新对话的最后活动时间
        updateConversationLastActivity(conversationId);
        
        Log.d(TAG, "Added message to conversation: " + conversationId);
    }
    
    /**
     * 获取对话的所有消息
     */
    public List<ChatMessage> getConversationMessages(String conversationId) {
        String messagesKey = KEY_MESSAGES_PREFIX + conversationId;
        String messagesJson = prefs.getString(messagesKey, "[]");
        
        Type listType = new TypeToken<List<ChatMessage>>(){}.getType();
        List<ChatMessage> messages = gson.fromJson(messagesJson, listType);
        
        return messages != null ? messages : new ArrayList<>();
    }
    
    /**
     * 获取所有对话
     */
    public List<Conversation> getAllConversations() {
        String conversationsJson = prefs.getString(KEY_CONVERSATIONS, "[]");
        
        Type listType = new TypeToken<List<Conversation>>(){}.getType();
        List<Conversation> conversations = gson.fromJson(conversationsJson, listType);
        
        return conversations != null ? conversations : new ArrayList<>();
    }
    
    /**
     * 更新对话标题
     */
    public void updateConversationTitle(String conversationId, String newTitle) {
        List<Conversation> conversations = getAllConversations();
        
        for (Conversation conv : conversations) {
            if (conv.getId().equals(conversationId)) {
                conv.setTitle(newTitle);
                break;
            }
        }
        
        saveConversations(conversations);
        Log.d(TAG, "Updated conversation title: " + conversationId + " - " + newTitle);
    }
    
    /**
     * 删除对话
     */
    public void deleteConversation(String conversationId) {
        // 删除对话记录
        List<Conversation> conversations = getAllConversations();
        conversations.removeIf(conv -> conv.getId().equals(conversationId));
        saveConversations(conversations);
        
        // 删除消息记录
        String messagesKey = KEY_MESSAGES_PREFIX + conversationId;
        prefs.edit().remove(messagesKey).apply();
        
        Log.d(TAG, "Deleted conversation: " + conversationId);
    }
    
    /**
     * 清空所有历史记录
     */
    public void clearAllHistory() {
        prefs.edit().clear().apply();
        Log.d(TAG, "Cleared all chat history");
    }
    
    /**
     * 获取对话统计信息
     */
    public ChatStatistics getStatistics() {
        List<Conversation> conversations = getAllConversations();
        int totalConversations = conversations.size();
        int totalMessages = 0;
        
        for (Conversation conv : conversations) {
            List<ChatMessage> messages = getConversationMessages(conv.getId());
            totalMessages += messages.size();
        }
        
        return new ChatStatistics(totalConversations, totalMessages);
    }
    
    private void saveConversations(List<Conversation> conversations) {
        String conversationsJson = gson.toJson(conversations);
        prefs.edit().putString(KEY_CONVERSATIONS, conversationsJson).apply();
    }
    
    private void updateConversationLastActivity(String conversationId) {
        List<Conversation> conversations = getAllConversations();
        String currentTime = dateFormat.format(new Date());
        
        for (Conversation conv : conversations) {
            if (conv.getId().equals(conversationId)) {
                conv.setLastActivity(currentTime);
                break;
            }
        }
        
        saveConversations(conversations);
    }
    
    /**
     * 检查对话是否为空（只有系统消息，没有用户消息）
     */
    public boolean isConversationEmpty(String conversationId) {
        List<ChatMessage> messages = getConversationMessages(conversationId);
        
        // 检查是否只有系统消息，没有用户消息
        for (ChatMessage message : messages) {
            if (message.getType() == ChatMessage.TYPE_USER) {
                return false; // 有用户消息，不是空对话
            }
        }
        
        return true; // 只有系统消息或没有消息，视为空对话
    }
    
    /**
     * 自动清理空对话
     * @return 清理的对话数量
     */
    public int cleanupEmptyConversations() {
        List<Conversation> conversations = getAllConversations();
        List<Conversation> conversationsToKeep = new ArrayList<>();
        int cleanedCount = 0;
        
        for (Conversation conv : conversations) {
            if (isConversationEmpty(conv.getId())) {
                // 删除消息记录
                String messagesKey = KEY_MESSAGES_PREFIX + conv.getId();
                prefs.edit().remove(messagesKey).apply();
                cleanedCount++;
                Log.d(TAG, "Cleaned empty conversation: " + conv.getId() + " - " + conv.getTitle());
            } else {
                conversationsToKeep.add(conv);
            }
        }
        
        // 保存清理后的对话列表
        if (cleanedCount > 0) {
            saveConversations(conversationsToKeep);
        }
        
        return cleanedCount;
    }
    
    /**
     * 检查对话标题是否为默认标题（未修改）
     */
    public boolean hasDefaultTitle(String conversationId) {
        List<Conversation> conversations = getAllConversations();
        
        for (Conversation conv : conversations) {
            if (conv.getId().equals(conversationId)) {
                String title = conv.getTitle();
                return title.equals("新对话") || 
                       title.equals("轮盘卜卦对话") || 
                       title.startsWith("对话 ");
            }
        }
        
        return false;
    }
    
    /**
     * 获取对话的当前标题
     */
    public String getConversationTitle(String conversationId) {
        List<Conversation> conversations = getAllConversations();
        
        for (Conversation conv : conversations) {
            if (conv.getId().equals(conversationId)) {
                return conv.getTitle();
            }
        }
        
        return null;
    }
    
    /**
     * 标记对话标题已修改（自动保存）
     */
    public void markConversationTitleModified(String conversationId, String newTitle) {
        updateConversationTitle(conversationId, newTitle);
        
        // 更新最后活动时间
        updateConversationLastActivity(conversationId);
        
        Log.d(TAG, "Auto-saved conversation with modified title: " + conversationId + " - " + newTitle);
    }
    
    /**
     * 检查对话是否值得保存（有实际内容）
     */
    public boolean isConversationWorthSaving(String conversationId) {
        List<ChatMessage> messages = getConversationMessages(conversationId);
        
        // 至少要有一条用户消息和一条AI回复
        boolean hasUserMessage = false;
        boolean hasAIMessage = false;
        
        for (ChatMessage message : messages) {
            if (message.getType() == ChatMessage.TYPE_USER) {
                hasUserMessage = true;
            } else if (message.getType() == ChatMessage.TYPE_AI) {
                hasAIMessage = true;
            }
        }
        
        return hasUserMessage && hasAIMessage;
    }
    
    /**
     * 对话实体类
     */
    public static class Conversation {
        private String id;
        private String title;
        private String createdAt;
        private String lastActivity;
        
        public Conversation(String id, String title, String createdAt) {
            this.id = id;
            this.title = title;
            this.createdAt = createdAt;
            this.lastActivity = createdAt;
        }
        
        // Getters and Setters
        public String getId() { return id; }
        public void setId(String id) { this.id = id; }
        
        public String getTitle() { return title; }
        public void setTitle(String title) { this.title = title; }
        
        public String getCreatedAt() { return createdAt; }
        public void setCreatedAt(String createdAt) { this.createdAt = createdAt; }
        
        public String getLastActivity() { return lastActivity; }
        public void setLastActivity(String lastActivity) { this.lastActivity = lastActivity; }
    }
    
    /**
     * 聊天消息实体类
     */
    public static class ChatMessage {
        public static final int TYPE_USER = 0;
        public static final int TYPE_AI = 1;
        public static final int TYPE_SYSTEM = 2;
        
        private int type;
        private String content;
        private String timestamp;
        
        public ChatMessage(int type, String content, String timestamp) {
            this.type = type;
            this.content = content;
            this.timestamp = timestamp;
        }
        
        // Getters and Setters
        public int getType() { return type; }
        public void setType(int type) { this.type = type; }
        
        public String getContent() { return content; }
        public void setContent(String content) { this.content = content; }
        
        public String getTimestamp() { return timestamp; }
        public void setTimestamp(String timestamp) { this.timestamp = timestamp; }
    }
    
    /**
     * 聊天统计信息
     */
    public static class ChatStatistics {
        private int totalConversations;
        private int totalMessages;
        
        public ChatStatistics(int totalConversations, int totalMessages) {
            this.totalConversations = totalConversations;
            this.totalMessages = totalMessages;
        }
        
        public int getTotalConversations() { return totalConversations; }
        public int getTotalMessages() { return totalMessages; }
    }
} 